package com.westos.calcv3.proxy;

import com.westos.calcv2.AddOperator;
import com.westos.calcv2.IOperator;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * java动态代理的实现
 */
public class DynProxy {

    public static void main(String[] args){
        Subject realSubject=new RealSubject();
        InvocationHandler proxyhandler=new ProxyHandler(realSubject);
        Subject proxySubject= (Subject) Proxy.newProxyInstance(Subject.class.getClassLoader(),new Class[]{Subject.class},proxyhandler);
        proxySubject.doSomething();

        // 使用动态代理在方法执行前检查参数
        IOperator add=new AddOperator();
        proxyhandler=new ProxyHandler(add);
        IOperator proxyOperator = (IOperator)Proxy.newProxyInstance(IOperator.class.getClassLoader(), new Class[]{IOperator.class}, proxyhandler);
        proxyOperator.operator(1,2);
        proxyOperator.operator(null,2);
    }
}